#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ROWS 10000
#define COLS 10000

void add_by_row(double** a, double** b, double** result) {
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            result[i][j] = a[i][j] + b[i][j];
        }
    }
}

void add_by_col(double** a, double** b, double** result) {
    for (int j = 0; j < COLS; j++) {
        for (int i = 0; i < ROWS; i++) {
            result[i][j] = a[i][j] + b[i][j];
        }
    }
}

int main() {
    // 动态分配内存
    double** a = (double**)malloc(ROWS * sizeof(double*));
    double** b = (double**)malloc(ROWS * sizeof(double*));
    double** result = (double**)malloc(ROWS * sizeof(double*));

    for (int i = 0; i < ROWS; i++) {
        a[i] = (double*)malloc(COLS * sizeof(double));
        b[i] = (double*)malloc(COLS * sizeof(double));
        result[i] = (double*)malloc(COLS * sizeof(double));

        for (int j = 0; j < COLS; j++) {
            a[i][j] = (double)rand() / RAND_MAX;
            b[i][j] = (double)rand() / RAND_MAX;
        }
    }

    // 测试按行加和
    clock_t start = clock();
    add_by_row(a, b, result);
    clock_t end = clock();
    double time_row = ((double)(end - start)) / CLOCKS_PER_SEC;
    printf("按行加和耗时: %.4f 秒\n", time_row);

    // 测试按列加和
    start = clock();
    add_by_col(a, b, result);
    end = clock();
    double time_col = ((double)(end - start)) / CLOCKS_PER_SEC;
    printf("按列加和耗时: %.4f 秒\n", time_col);

    printf("按行比按列快 %.2f 倍\n", time_col / time_row);

    // 释放内存
    for (int i = 0; i < ROWS; i++) {
        free(a[i]);
        free(b[i]);
        free(result[i]);
    }
    free(a);
    free(b);
    free(result);

    return 0;
}
/*
输出结果为：
按行加和耗时: 0.3980 秒
按列加和耗时: 2.8570 秒
按行比按列快 7.18 倍
*/
